<?php

declare ( strict_types = 1 )
	;

namespace Distributed\Event;

use Distributed\Contract\IEvent;
use UntilDistributed\Log;
use Distributed\Group\TransGroupManage;
use Exception;
use Communication\TxSocketData;
use Distributed\Constant;
use Distributed\Group\TransactionManage;

/**
 *
 * @author mg
 *        
 */
class RollBack extends AbstractEvent implements IEvent {
	/**
	 *
	 * {@inheritdoc}
	 *
	 * @see \Distributed\Contract\IEvent::parseEvent()
	 */
	public function parseEvent(int $fd): ?TxSocketData {
		
		
		$groupId = $this->data->transGroup->groupId;
		
		try {
			Log::getInstance ()->info ( "txmanage rollback start" );
			
			// 查找事务组信息
			$transactionList = TransGroupManage::getInstance ()->getItemsByGroupId ( $groupId );
			if (empty ( $transactionList )) {
				throw new Exception ( "rollback cancel : have no transaction actor", 10001 );
			}
			
			TransGroupManage::getInstance ()->updateItemStatus ( $groupId, $this->data->transaction, Constant::$tx_status_rollback );
			
			
			TransactionManage::getInstance ()->rollback ( $groupId );
			
		} catch ( Exception $e ) {
			var_dump ( $e->getMessage () );
			Log::getInstance ()->error ( $e->getMessage () );
			// 通知发起者回滚
			return TxSocketData::createResponse ( Constant::$tx_complete_fail );
		}
		
		Log::getInstance ()->info ( "txmanage rollback end" );
		
		TransGroupManage::getInstance ()->delGroup($groupId);
		return null;
	}
}